﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using CADTool.DotNetARX;
using CADTool.FIleReadWrite;
using CADTool.Jig;
using CADTool.TestTool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.RightsManagement;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Ink;

namespace CADTool
{
    public class CADTool
    {
        //显示窗体
        [CommandMethod("ShowForm")]
        public static void ShowForm()
        {
            CADForm m_Form = new CADForm();
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(m_Form);
        }
        //生成地块功能    
        [CommandMethod("SCDK")]
        public static void SCDK()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            DocumentLock documentLock = doc.LockDocument();
            try
            {
                string path = CustomMethod.FileNameForOpen("\n请选择文件");
                string[] contens = File.ReadAllLines(path, Encoding.UTF8);
                string[] bsf = new string[contens.Length];
                List<Point2d> points = new List<Point2d>();
                for (int i = 0; i < contens.Length; i++)
                {
                    string[] temp = contens[i].Split(';');
                    points.Add(new Point2d(Convert.ToDouble(temp[1]), Convert.ToDouble(temp[2])));
                    bsf[i] = temp[3];
                }
                for (int i = 0; i < contens.Length - 1; i++)
                {
                    if (bsf[i] == "")
                    {
                        CustomMethod.AddLineToModelSpace(points[i], points[i + 1]);
                    }
                    else if (bsf[i] == "BC")
                    {
                        CustomMethod.AddCirToModelSpace(points[i], points[i + 1], points[i + 2]);
                    }
                    else if (bsf[i] == "MC" || bsf[i] == "D")
                    {
                        continue;
                    }
                }
                bool onlyOne = true;
                if (onlyOne)
                {
                    doc.SendStringToExecute("_zoom e ", true, false, false);
                    onlyOne = false;
                }
            }
            catch (System.Exception)
            {
                Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
                ed.WriteMessage("格式不正确或未知错误......");
            }
            documentLock.Dispose();
        }
        //横向阵列
        [CommandMethod("DXZL")]
        public static void DXZL()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Point3d p1 = new Point3d();
            Point3d p2 = new Point3d();
            Entity ent = SelectTool.SelectEntity("\n请选择要阵列的实体");
            if (ent == null) return;
            PromptPointOptions ppo = new PromptPointOptions("\n请指定偏移点");
            ppo.AllowNone = false;
            PromptPointResult ppr = ed.GetPoint(ppo);
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK) p1 = ppr.Value;
            ppo.Message = "\n请选择目标点";
            ppo.BasePoint = p1;
            ppo.UseBasePoint = true;
            ppr = ed.GetPoint(ppo);
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK) p2 = ppr.Value;
            PromptIntegerResult pdr = ed.GetInteger("\n请输入要复制得个数");
            int num = (int)pdr.Value;
            Vector3d vec = p2 - p1;
            ent.CopyAndOffset(vec, num);
            documentLock.Dispose();
        }
        //对比标注功能
        [CommandMethod("DBBZ")]
        public static void DBBZ()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions ppo = new PromptPointOptions("\n请指定第一个点");
            ppo.AllowNone = false;
            PromptPointResult ppr = CustomMethod.GetPoint(ppo);
            Point3d p1 = new Point3d(0, 0, 0);
            Point3d p2 = new Point3d();
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK) p1 = ppr.Value;
            ppo.Message = "\n请指定第二个点";
            ppo.BasePoint = p1;
            ppo.UseBasePoint = true;
            ppr = CustomMethod.GetPoint(ppo);
            if (ppr.Status == PromptStatus.None) return;
            if (ppr.Status == PromptStatus.OK) p2 = ppr.Value;
            //记录标注的长度
            ed.WriteMessage("\n两点之间的距离为:" + Math.Round(CustomMethod.GetDistanceBetweenTowPoint(p1, p2), 3).ToString("0.000"));
            double scDis = Math.Round(CustomMethod.GetDistanceBetweenTowPoint(p1, p2), 3);
            PromptResult pr = ed.GetString("\n请输入设计值");
            //记录设计值
            double sjDis;
            try
            {
                sjDis = Convert.ToDouble(pr.StringResult);
            }
            catch (System.Exception)
            {

                sjDis = 0;
            }
            //标注线
            List<Point3d> pt3d = new List<Point3d>();
            pt3d = CustomMethod.PointOffset(p1, p2, -0.6);

            //标注内容
            DBText text1 = new DBText();
            text1.Position = pt3d[1];
            text1.TextString = "(设计值" + Math.Round(sjDis, 3).ToString("0.000") + "较差" + (scDis - sjDis).ToString("0.000") + ")";
            text1.Height = 1;
            text1.Rotation = CustomMethod.GetAngleToXaxis(p1, p2);
            text1.HorizontalMode = TextHorizontalMode.TextCenter;
            text1.VerticalMode = TextVerticalMode.TextTop;
            text1.AlignmentPoint = text1.Position;
            //开启事务处理
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //打开块表
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                //打开块表
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                //添加图形到块表记录
                btr.AppendEntity(text1);
                //更新数据信息
                trans.AddNewlyCreatedDBObject(text1, true);
                //提交事务
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //自动将多段线的端点悬挂到附近点上
        [CommandMethod("ZDXGD")]
        public static void ZDXGD()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            //存储多段线
            List<Polyline> pls = new List<Polyline>();
            //存储多段线的点
            List<Point3d> pointsL = new List<Point3d>();
            //存储悬挂点
            List<Point3d> points = new List<Point3d>();
            List<Entity> entities = CustomMethod.SelectEntitys();
            //遍历实体
            if (entities == null) return;
            foreach (Entity item in entities)
            {
                //将多段线筛选出来
                if (item is Polyline pl)
                {
                    pls.Add(pl);
                }
                //将悬挂点筛选出来
                if (item is DBPoint xgd)
                {
                    points.Add(xgd.Position);
                }
            }
            //将多段线的点读取出来
            //将多段线的点读取出来
            Point3d temp = new Point3d();
            for (int i = 0; i < pls.Count; i++)
            {
                for (int j = 0; j < pls[i].NumberOfVertices; j++)
                {
                    temp = pls[i].GetPoint3dAt(j).Nearset(points);
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        Circle c = new Circle()
                        {
                            Center = new Point3d(temp.X, temp.Y, 0),
                            Radius = 10
                        };
                        CustomMethod.AddEntityToModelSpace(db, c);
                        pls[i].Id.GetObject(OpenMode.ForWrite);
                        pls[i].SetPointAt(j, temp.ToPoint2d());
                        pls[i].DowngradeOpen();
                        trans.Commit();
                    }

                }
            }
            documentLock.Dispose();
        }
        //求和功能：数字前后可以有其他字符，不能为多行文字
        [CommandMethod("SZQH")]
        public static void SZQH()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            List<Entity> ents = CustomMethod.SelectEntitys();
            List<Entity> txts = new List<Entity>();
            if (ents == null) return;
            foreach (Entity item in ents)
            {
                if (item is DBText)
                {
                    txts.Add(item);
                }
            }
            string str = null;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                double sum = 0;
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                foreach (var item in txts)
                {
                    DBText txt = (DBText)trans.GetObject(item.ObjectId, OpenMode.ForRead);
                    if ((txt.TextString).IsContainNumbre())
                    {
                        str = Regex.Replace(txt.TextString, @"[^\d.\d]", "");
                        sum += Convert.ToDouble(str);
                    }
                }
                DBText sumTxt = new DBText();
                sumTxt.TextString = sum.ToString();
                sumTxt.Height = 10;
                JigDBText jigDBText = new JigDBText(sumTxt, new Point3d(0, 0, 0));
                PromptResult pr = Application.DocumentManager.MdiActiveDocument.Editor.Drag(jigDBText);
                if (pr.Status == PromptStatus.OK)
                {
                    CustomMethod.AddEntityToModelSpace(db, sumTxt);
                }
                //PromptPointOptions ppo = new PromptPointOptions("请放置文字...");
                //Point3d basePoint = ed.GetPoint(ppo).Value;
                //DBText sumTxt = new DBText();
                //sumTxt.TextString = sum.ToString();
                //sumTxt.Position = basePoint;
                //btr.AppendEntity(sumTxt);
                //trans.AddNewlyCreatedDBObject(sumTxt, true);
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //智能求和
        [CommandMethod("ZNQH")]
        public static void ZNQH()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            CustomMethod.GetFocus();
            List<DBText> txts = SelectTool.SelectDBtext("请选择带数字的字符串");
            List<double> tempDouble = new List<double>();
            double sum = 0;
            foreach (var item in txts)
            {
                if (!item.TextString.IsContainNumbre())
                {
                    tempDouble.Add(0);
                }
                else
                {
                    tempDouble.Add(item.TextString.ExtractMaxNum());
                }
            }
            foreach (var item in tempDouble)
            {
                sum += item;
            }
            DBText sumText = new DBText();
            sumText.TextString = sum.ToString("0.000000000");
            sumText.Height = 10;
            sumText.TextStyleId = txts[0].TextStyleId;
            JigDBText jigDBText = new JigDBText(sumText, new Point3d(0, 0, 0));
            PromptResult pr = Z.ed.Drag(jigDBText);
            if (pr.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(Z.db, sumText);
            }
            documentLock.Dispose();
        }
        //求差功能
        [CommandMethod("SZXJ")]
        public static void SZXJ()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            CustomMethod.GetFocus();
            List<DBText> txts = SelectTool.SelectDBtext("请选择数字或带数字的字符串");
            List<double> tempDouble = new List<double>();
            foreach (var item in txts)
            {
                if (!item.TextString.IsContainNumbre())
                {
                    tempDouble.Add(0);
                }
                else
                {
                    tempDouble.Add(item.TextString.ExtractMaxNum());
                }
            }
            double sum = 0;
            if (tempDouble.Count == 0) return;
            if (tempDouble.Count == 1)
            {
                sum = tempDouble[0];
            }
            else
            {
                sum = 2 * tempDouble[0];
                for (int i = 0; i < tempDouble.Count; i++)
                {
                    sum -= tempDouble[i];
                }

            }
            DBText sumText = new DBText();
            sumText.TextString = sum.ToString("0.000000000");
            sumText.TextStyleId = txts[0].TextStyleId;
            sumText.Height = txts[0].Height;
            sumText.ColorIndex = txts[0].ColorIndex;
            sumText.LayerId = txts[0].LayerId;
            JigDBText jigDBText = new JigDBText(sumText, new Point3d(0, 0, 0));
            PromptResult pr = Z.ed.Drag(jigDBText);
            if (pr.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(Z.db, sumText);
            }
            documentLock.Dispose();
        }
        //包围盒子任意数量实体
        [CommandMethod("BWHZ")]
        public static void BWHZ()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Editor ed = doc.Editor;
            Database db = HostApplicationServices.WorkingDatabase;
            try
            {
                List<Entity> ents = SelectTool.SelectEntities();
                if (ents == null) return;
                Tuple<Point3d, Point3d> tuple = CustomMethod.GetBoxPoint(ents);
                Point3d minPo = tuple.Item1;
                Point3d maxPo = tuple.Item2;
                db.AddLineToModelSpace(minPo, new Point3d(maxPo.X, minPo.Y, 0));
                db.AddLineToModelSpace(minPo, new Point3d(minPo.X, maxPo.Y, 0));
                db.AddLineToModelSpace(maxPo, new Point3d(minPo.X, maxPo.Y, 0));
                db.AddLineToModelSpace(maxPo, new Point3d(maxPo.X, minPo.Y, 0));
            }
            catch (System.Exception)
            {
                ed.WriteMessage("未按照预期流程操作......");
            }

            documentLock.Dispose();
        }
        //公司名称
        [CommandMethod("GSMC")]
        public static void GSMC()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock documentLock = doc.LockDocument();
            doc.Window.Focus();
            Point3d position = new Point3d(0, 0, 0);
            DBText txt = new DBText();
            txt.TextString = "北京新航城智慧数字科技有限公司";
            txt.Height = 10;
            txt.Position = position;
            txt.SetDatabaseDefaults(db);
            JigDBText jigDBText = new JigDBText(txt, position);
            PromptResult pr = Application.DocumentManager.MdiActiveDocument.Editor.Drag(jigDBText);
            if (pr.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(db, jigDBText.txt);
            }
            documentLock.Dispose();
        }
        //打开所有图层
        [CommandMethod("OpenAllLayers")]
        public static void OpenAllLayers()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            DocumentLock documentLock = doc.LockDocument();
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = trans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                foreach (ObjectId item in lt)
                {
                    LayerTableRecord ltr = item.GetObject(OpenMode.ForWrite) as LayerTableRecord;
                    if (ltr.IsOff)
                    {
                        ltr.IsOff = false;
                    }
                }
                trans.Commit();
            }
            documentLock.Dispose();
            doc.Window.Focus();
        }
        //关闭所有图层
        [CommandMethod("CloseAllLayers")]
        public static void CloseAllLayers()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            DocumentLock documentLock = doc.LockDocument();
            doc.Window.Focus();
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                LayerTable lt = trans.GetObject(db.LayerTableId, OpenMode.ForWrite) as LayerTable;
                foreach (ObjectId item in lt)
                {
                    LayerTableRecord ltr = item.GetObject(OpenMode.ForWrite) as LayerTableRecord;
                    if (!ltr.IsOff)
                    {
                        ltr.IsOff = true;
                    }
                }
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //置为当前层
        [CommandMethod("ZWDQC")]
        public static void ZWDQC()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            PromptEntityOptions peo = new PromptEntityOptions("\n请选择要置为当前层的实体");
            PromptEntityResult per = Z.ed.GetEntity(peo);
            if (per.Status == PromptStatus.OK)
            {
                using (Transaction trans = Z.db.TransactionManager.StartTransaction())
                {
                    Entity ent = (Entity)trans.GetObject(per.ObjectId, OpenMode.ForWrite);
                    Z.db.Clayer = ent.LayerId;
                    trans.Commit();
                }
            }
            Z.ed.Regen();
            documentLock.Dispose();
        }
        //关闭选中层
        [CommandMethod("CloseSelectedLayer")]
        public static void CloseSelectedLayer()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            List<Entity> entities = CustomMethod.SelectEntitys();
            if (entities == null || entities.Count == 0) return;
            foreach (var item in entities)
            {
                item.Layer.CloseThisLayer();
            }
            documentLock.Dispose();
        }
        //只显示选中层
        public static void OnlyShowSelectedLayer()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            List<Entity> entities = CustomMethod.SelectEntitys();
            if (entities == null || entities.Count == 0) return;
            foreach (var item in entities)
            {
                item.Layer.CloseBesidesLayeres();
            }
            documentLock.Dispose();
        }
        //复制到当前层
        [CommandMethod("CopyToThisLayer")]
        public static void CopyToThisLayer()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            doc.Window.Focus();
            DocumentLock documentLock = doc.LockDocument();
            Database db = doc.Database;
            Editor ed = doc.Editor;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //选择要克隆得实体
                PromptEntityOptions peo = new PromptEntityOptions("选择要克隆的实体");
                peo.SetRejectMessage("只能选择一个实体");
                peo.AddAllowedClass(typeof(Entity), false);
                PromptEntityResult per = ed.GetEntity(peo);
                if (per.Status != PromptStatus.OK) return;
                Entity ent = (Entity)trans.GetObject(per.ObjectId, OpenMode.ForRead);
                //克隆实体
                Entity cloneEnt = ent.Clone() as Entity;
                if (cloneEnt == null) return;
                //获取当前图层
                ObjectId currentLayerId = db.Clayer;
                //将克隆实体添加到当前图层
                cloneEnt.LayerId = currentLayerId;
                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                btr.AppendEntity(cloneEnt);
                trans.AddNewlyCreatedDBObject(cloneEnt, true);
                trans.Commit();
            }
            ed.WriteMessage($"\n已将实体克隆到当前图层");
            documentLock.Dispose();
        }
        //移动到当前图层
        [CommandMethod("MoveToThisLayer")]
        public static void MoveToThisLayer()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            DocumentLock documentLock = doc.LockDocument();
            doc.Window.Focus();
            Database db = doc.Database;
            Editor ed = doc.Editor;
            var peo = new PromptEntityOptions("\n请选择实体");
            PromptEntityResult per = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK) return;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                Entity ent = (Entity)trans.GetObject(per.ObjectId, OpenMode.ForWrite);
                if (ent != null)
                {
                    ent.LayerId = db.Clayer;
                }
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //单行文本合并
        [CommandMethod("WBHB")]
        public static void WBHB()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            DocumentLock documentLock = doc.LockDocument();
            doc.Window.Focus();
            Database db = doc.Database;
            Editor ed = doc.Editor;
            string str1 = "";
            string str2 = "";
            DBText txt = new DBText();
            Entity ent1 = SelectTool.SelectEntity("\n请选择第一个单行文字");
            if (ent1 != null && ent1 is DBText txt1)
            {
                str1 = txt1.TextString;
                Entity ent2 = SelectTool.SelectEntity("\n请选择第二个单行文字");
                if (ent1 != null && ent2 is DBText txt2)
                {
                    str2 = txt2.TextString;
                    txt.TextString = str1 + str2;
                    txt.TextStyleId = txt1.TextStyleId;
                    txt.Height = txt1.Height;
                    txt.ColorIndex = txt1.ColorIndex;
                }
            }
            Point3d p0 = new Point3d();
            JigDBText jigDBText = new JigDBText(txt, p0);
            PromptResult pr = Application.DocumentManager.MdiActiveDocument.Editor.Drag(jigDBText);
            if (pr.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(db, txt);
            }
            documentLock.Dispose();
        }
        //求多个实体的面积
        [CommandMethod("MJHZ")]
        public static void MJHZ()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            List<Entity> entities = CustomMethod.SelectEntitys();
            if (entities == null) return;
            List<Curve> curves = new List<Curve>();
            double temp = 0;
            foreach (var item in entities)
            {
                if (item is Curve curve && curve.Closed == true)
                {
                    curves.Add(curve);
                    temp += curve.Area;
                }
            }
            DBText txt = new DBText();
            txt.TextString = temp.ToString();
            txt.Height = 10;
            Point3d p0 = new Point3d();
            JigDBText jigDBText = new JigDBText(txt, p0);
            PromptResult pr = Application.DocumentManager.MdiActiveDocument.Editor.Drag(jigDBText);
            if (pr.Status == PromptStatus.OK)
            {
                Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"共选择{curves.Count}个封闭实体...");
                CustomMethod.AddEntityToModelSpace(db, txt);
            }
        }
        //坐标标注  -----未完成
        [CommandMethod("ZBBZ")]
        public static void ZBBZ()
        {

        }
        //实体前置
        [CommandMethod("STQZ")]
        public static void STQZ()
        {
            CustomMethod.GetFocus();
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = SelectTool.SelectEntity("\n请选择要前置的实体");
                CustomMethod.MoveTop(ent, db);
                trans.Commit();
            }
        }
        //实体后置
        [CommandMethod("STHZ")]
        public static void STHZ()
        {
            CustomMethod.GetFocus();
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = SelectTool.SelectEntity("\n请选择要后置的实体");
                DBText txt = new DBText();

                CustomMethod.MoveBottom(ent, db);
                trans.Commit();
            }
        }
        //将多个单行文字纵向对齐
        [CommandMethod("ZXDQ")]
        public static void ZXDQ()
        {
            CustomMethod.GetFocus();
            List<DBText> txts = SelectTool.SelectDBtext("请选择要对齐的文字");
            CustomMethod.AlignTextVertically(txts);
        }
        //文字横向对齐
        [CommandMethod("WZHDQ")]
        public static void WZHDQ()
        {
            CustomMethod.GetFocus();
            List<DBText> txts = SelectTool.SelectDBtext("请选择要对齐的文字");
            CustomMethod.AlignTextHorizontal(txts);
        }
        //多行文字转单行文字
        [CommandMethod("MtextToDBText")]
        public static void MtextToDBText()
        {
            CustomMethod.GetFocus();
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            PromptEntityOptions peo = new PromptEntityOptions("\n选择一个多行文字转为单行文字");
            peo.SetRejectMessage("\n请选择一个多行文字");
            PromptEntityResult per = ed.GetEntity(peo);
            if (per.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\n没有选择到多行文字");
            }
            Transaction trans = db.TransactionManager.StartTransaction();
            using (trans)
            {
                MText mtext = trans.GetObject(per.ObjectId, OpenMode.ForWrite) as MText;
                if (mtext == null)
                {
                    ed.WriteMessage("\n无法打开文本对象进行写入");
                    return;
                }
                //转换多行文本
                DBText dBText = new DBText();
                dBText.Position = mtext.Location;
                dBText.Height = 10;
                dBText.Rotation = mtext.Rotation;
                dBText.TextString = mtext.Text.ToString();
                //复制多行文字样式
                dBText.TextStyleId = mtext.TextStyleId;
                //删除多行文字
                mtext.Erase();
                //添加DBText到模型空间
                BlockTableRecord currentSpace = trans.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                currentSpace.AppendEntity(dBText);
                trans.AddNewlyCreatedDBObject(dBText, true);
                trans.Commit();
            }
        }
        //随机颜色
        [CommandMethod("SJYS")]
        public static void SJYS()
        {
            CustomMethod.GetFocus();
            List<Entity> ents = Z.PinkList<Entity>();
            System.Random r = new System.Random();

            if (ents.Count == 0) return;
            foreach (Entity ent in ents)
            {
                ent.Id.ChangeColor(Convert.ToByte(r.Next(0, 255)));
            }
        }
        //多数字提取
        [CommandMethod("DSZTQ")]
        public static void DSZTQ()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Z.doc.LockDocument();
            Entity ent = SelectTool.SelectEntity("\n请选择文字");
            List<string> strs = new List<string>();
            List<DBText> texts = new List<DBText>();
            if (ent == null) return;
            if (ent is DBText dBText)
            {
                strs = dBText.TextString.Numbers();
                strs.Reverse();
                for (int i = 0; i < strs.Count; i++)
                {
                    DBText txt = new DBText();
                    txt.TextStyleId = dBText.TextStyleId;
                    txt.Height = dBText.Height;
                    txt.ColorIndex = dBText.ColorIndex;
                    txt.TextString = strs[i];
                    txt.LayerId = dBText.LayerId;
                    texts.Add(txt);
                }
            }
            JigListDBtext jigListDBtext = new JigListDBtext(new Point3d(0, 0, 0), texts);
            PromptResult resJig = Z.ed.Drag(jigListDBtext);
            if (resJig.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(Z.db, jigListDBtext.GetEntity());
            }
            documentLock.Dispose();
        }
        //摆正图纸（会改变图纸坐标）
        [CommandMethod("BZTZ")]
        public static void BZTZ()
        {
            CustomMethod.GetFocus();
            double rad = 0;
            PromptPointOptions ppo = new PromptPointOptions("\n请选择第一点");
            PromptPointResult ppr = Z.ed.GetPoint(ppo);
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK)
            {
                Point3d p1 = ppr.Value;
                ppo.Message = "\n请选择第二点";
                ppo.UseBasePoint = true;
                ppo.BasePoint = ppr.Value;
                ppr = Z.ed.GetPoint(ppo);
                if (ppr.Status == PromptStatus.Cancel) return;
                if (ppr.Status == PromptStatus.OK)
                {
                    Point3d p2 = ppr.Value;
                    Line line = new Line(p1, p2);
                    rad = line.Angle.RedToAng();
                }
                string str1 = "UCS ";
                string str2 = "Z ";
                string str3 = rad.ToString() + " ";
                string str4 = "plan ";
                string command = str1 + str2 + str3 + str4;
                CustomMethod.SendCommand(command);
            }
        }
        //超级摆正（不会改变图纸的坐标）
        [CommandMethod("CJBZ")]
        public static void CJBZ()
        {
            CustomMethod.GetFocus();
            double rad = 0;
            PromptPointOptions ppo = new PromptPointOptions("\n请选择第一点");
            PromptPointResult ppr = Z.ed.GetPoint(ppo);
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK)
            {
                Point3d p1 = ppr.Value;
                ppo.Message = "\n请选择第二点";
                ppo.UseBasePoint = true;
                ppo.BasePoint = ppr.Value;
                ppr = Z.ed.GetPoint(ppo);
                if (ppr.Status == PromptStatus.Cancel) return;
                if (ppr.Status == PromptStatus.OK)
                {
                    Point3d p2 = ppr.Value;
                    Line line = new Line(p1, p2);
                    rad = -line.Angle.RedToAng();
                }
                string str = rad.ToString() + " ";
                PromptSelectionResult psr = Z.ed.SelectAll();
                if (psr.Status != PromptStatus.OK) return;
                Z.ed.SetImpliedSelection(psr.Value);
                CustomMethod.SendCommand("DVIEW " + "TW " + str);
            }
        }
        //恢复视图到正常模式
        [CommandMethod("HFST")]
        public static void HFST()
        {
            CustomMethod.SendCommand("\u001b_-view " + "_top");
        }
        //拦截文字编辑器
        [CommandMethod("LJWZBJ")]
        public static void LJWZBJ()
        {
            Application.DocumentManager.DocumentLockModeChanged -= DocumentManager_DocumentLockModeChanged;
            Application.DocumentManager.DocumentLockModeChanged += DocumentManager_DocumentLockModeChanged;
        }
        //取消文字编辑器拦截
        [CommandMethod("QXLJ")]
        public static void QXLJ()
        {
            Z.ed.WriteMessage("\n拦截已失效");
            Application.DocumentManager.DocumentLockModeChanged -= DocumentManager_DocumentLockModeChanged;
        }
        private static void DocumentManager_DocumentLockModeChanged(object sender, DocumentLockModeChangedEventArgs e)
        {

            if (e.GlobalCommandName.ToUpper() != "TEXTEDIT") return;
            var r1 = Z.ed.SelectImplied();
            if (r1.Status != PromptStatus.OK) return;
            if (r1.Value.Count != 1) return;
            var id = r1.Value[0].ObjectId;
            if (id.IsOK() || !id.ObjectClass.IsDerivedFrom(RXClass.GetClass(typeof(DBText)))) return;
            Z.ed.WriteMessage("\n拦截成功");
            e.Veto();
            DBText text;
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                text = trans.GetObject(id, OpenMode.ForWrite) as DBText;
                var ltr = trans.GetObject(text.LayerId, OpenMode.ForRead) as LayerTableRecord;
                if (ltr.IsLocked) return;
                Application.DocumentManager.DocumentLockModeChanged -= DocumentManager_DocumentLockModeChanged;
                try
                {
                    var str = Microsoft.VisualBasic.Interaction.InputBox("请输入文字", "文本编辑器", text.TextString);
                    if (str is null || str.Trim() == "" || str == text.TextString) return;
                    text.TextString = str;
                }
                finally
                {
                    Application.DocumentManager.DocumentLockModeChanged += DocumentManager_DocumentLockModeChanged;
                }
                trans.Commit();
            }
        }
        //加常数或减常数
        [CommandMethod("JCS")]
        public static void JCS()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Z.doc.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            List<DBText> dBTexts = SelectTool.SelectDBtext("\n请选择单个或多个文字");
            if (dBTexts.Count == 0) return;
            double tempDouble = 0;
            string tempNum = Microsoft.VisualBasic.Interaction.InputBox("请输入要加的常数：", "加常数对话框", "");
            try
            {
                tempDouble = Convert.ToDouble(tempNum);
            }
            catch (System.Exception)
            {
                Z.ed.WriteMessage("\n输入有误，或者为非数字");
            }
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {

                foreach (DBText text in dBTexts)
                {
                    trans.GetObject(text.Id, OpenMode.ForWrite);
                    try
                    {
                        text.TextString = (Convert.ToDouble(text.TextString) + tempDouble).ToString();
                    }
                    catch (System.Exception)
                    {
                        Z.ed.WriteMessage("\n存在非法值，已跳过");
                    }
                }
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //修改图层名称
        [CommandMethod("XGCM")]
        public static void XGCM()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            DocumentLock documentLock = Z.doc.LockDocument();
            Entity ent = SelectTool.SelectEntity("\n请选择要修改图层上的任意一个实体");
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                trans.GetObject(ent.Id, OpenMode.ForRead);
                if (ent.Layer == "0" || ent.Layer == "Defpoints")
                {
                    Z.ed.WriteMessage("\n不得对0层及Defpoints重新命名");
                    return;
                }
                //打开层表
                LayerTable lt = trans.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                //提示用户输入图层名
                PromptStringOptions pso = new PromptStringOptions("\n请输入图层名称");
                PromptResult pr = Z.ed.GetString(pso);
                if (pr.Status != PromptStatus.OK) return;
                try
                {
                    //验证输入字符串是否符合符号表的命名规则
                    SymbolUtilityServices.ValidateSymbolName(pr.StringResult, false);
                    if (lt.Has(ent.Layer))
                    {
                        //获得要修改的层
                        LayerTableRecord ltr = trans.GetObject(lt[ent.Layer], OpenMode.ForWrite) as LayerTableRecord;
                        ltr.Name = pr.StringResult;
                    }
                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    //捕捉到异常，图层名不合法
                    Z.ed.WriteMessage(ex.Message + "\n");
                }
                trans.Commit();
            }
            documentLock.Dispose();
        }
        //数字取位
        [CommandMethod("SZQW")]
        public static void SZQW()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            CustomMethod.GetFocus();
            List<DBText> txts = SelectTool.SelectDBtext("\n请选择要取位的数字");
            int num;
            string str = "0."; //记录格式化字符串
            PromptStringOptions pso = new PromptStringOptions("\n请输入要取几位");
            pso.DefaultValue = "0";
            PromptResult pr = Z.ed.GetString(pso);
            pso.AllowSpaces = true;
            PromptKeywordOptions keyWord = new PromptKeywordOptions("\n是否补零？[补零(Y)/不补零(N)]<Y>");
            keyWord.Keywords.Add("Y");
            keyWord.Keywords.Add("N");
            keyWord.Keywords.Default = "Y";
            keyWord.AppendKeywordsToMessage = false;
            if (pr.Status == PromptStatus.OK)
            {
                PromptResult pKeyRes = Z.ed.GetKeywords(keyWord);
                if (pKeyRes.StringResult == "Y")
                {
                    int numWs = Convert.ToInt16(pr.StringResult);
                    for (int i = 0; i < numWs; i++)
                    {
                        str += "0";
                    }
                }
                else str = "";
                try
                {
                    num = Convert.ToInt16((pr.StringResult));
                }
                catch (System.Exception)
                {
                    Z.ed.WriteMessage("\n输入有误");
                    return;
                };
                using (Transaction trans = Z.db.TransactionManager.StartTransaction())
                {
                    foreach (var item in txts)
                    {
                        trans.GetObject(item.Id, OpenMode.ForWrite);
                        try
                        {
                            item.TextString = Convert.ToDouble(item.TextString).ToString(str);
                        }
                        catch (System.Exception)
                        {
                            Z.ed.WriteMessage($"\n存在非法值----{item.TextString}---- 已跳过");
                            continue;
                        }
                    }
                    trans.Commit();
                }
            }
            documentLock.Dispose();

        }
        //托盘和气泡通知
        [CommandMethod("TPQPTZ")]
        public static void TPQPTZ()
        {
            //设置系统变量避免由于系统变量导致气泡无法弹出 设置为0气泡无法弹出
            Application.SetSystemVariable("TrayIcons", 1);
            Application.SetSystemVariable("TrayNotify", 1);
            //设置气泡的持续时间单位是秒
            Application.SetSystemVariable("TrayTimeOut", 3);
            var statusBar = Application.StatusBar;
            var ti = statusBar.GetTrayItem();
            var tibw = new TrayItemBubbleWindow()
            {
                IconType = IconType.None,
                Title = "提示",
                Text = "\nYZQ-CADTool加载成功!\n",
            };
            ti.ShowBubbleWindow(tibw);
        }
        //计算图形外轮廓
        [CommandMethod("TXWLK")]
        public static void TXWLK()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            Z.ed.WriteMessage("\n请选择要生成外轮廓的图形");
            List<Entity> ents = SelectTool.SelectEntities();
            if (ents.Count == 0) return;
            List<Curve> curves = ents.FindAll(x => x is Curve).Select(x => x as Curve).ToList();
            double minx = ents.Min(x => x.Bounds.Value.MinPoint.X) - 10;
            double miny = ents.Min(x => x.Bounds.Value.MinPoint.Y) - 10;
            double maxx = ents.Max(x => x.Bounds.Value.MaxPoint.X) + 10;
            double maxy = ents.Max(x => x.Bounds.Value.MaxPoint.Y) + 10;
            Polyline polyline = new Polyline();
            polyline.AddVertexAt(0, new Point2d(minx, miny), 0, 0, 0);
            polyline.AddVertexAt(1, new Point2d(minx, maxy), 0, 0, 0);
            polyline.AddVertexAt(2, new Point2d(maxx, maxy), 0, 0, 0);
            polyline.AddVertexAt(3, new Point2d(maxx, miny), 0, 0, 0);
            polyline.Closed = true;
            CustomMethod.AddEntities(new List<Entity> { polyline });
            var dbs = Z.ed.TraceBoundary(new Point3d(minx + 5, miny + 5, 0), true);
            List<Entity> ss = new List<Entity>();
            foreach (Entity item in dbs)
            {
                if (item.Bounds.Value.MinPoint.X != minx)
                {
                    item.Color = Autodesk.AutoCAD.Colors.Color.FromRgb(255, 255, 0);
                    ss.Add(item);
                }
            }
            CustomMethod.EraseEntities(new List<Entity>() { polyline });
            CustomMethod.AddEntities(ss);
            documentLock.Dispose();
        }
        //生成矩形随机点
        [CommandMethod("SCSJD")]
        public static void SCSJD()
        {
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            //获取用户输入的起点和终点
            PromptPointOptions ppo = new PromptPointOptions("\n请输入矩形起点");
            PromptPointResult ppr = Z.ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK) return;
            Point3d startPoint = ppr.Value;
            Point3d endPoint = new Point3d();
            RectangleJig rectangleJig = new RectangleJig(startPoint, endPoint);
            Z.ed.Drag(rectangleJig);

            //确定绘制点的数量
            int numPoint = 0;
            PromptIntegerOptions pio = new PromptIntegerOptions("\n请输入要绘制的点的个数");
            pio.AllowNone = false;
            PromptIntegerResult pir = Z.ed.GetInteger(pio);
            //创建进度条
            ProgressMeter pm = new ProgressMeter();
            if (pir.Status == PromptStatus.OK)
            {
                numPoint = pir.Value;
            }
            else return;
            Point3d minPt;
            Point3d maxPt;
            if (rectangleJig._startPoint.X > rectangleJig._endPoint.X)
            {
                minPt = rectangleJig._endPoint;
                maxPt = rectangleJig._startPoint;
            }
            else
            {
                minPt = rectangleJig._startPoint;
                maxPt = rectangleJig._endPoint;
            }
            Random rand = new Random();
            List<DBPoint> dbPoint = new List<DBPoint>();
            pm.SetLimit(numPoint);
            pm.Start("正在生成随机点");
            for (int i = 0; i < numPoint; i++)
            {
                double x = rand.NextDouble() * (maxPt.X - minPt.X) + minPt.X;
                double y = rand.NextDouble() * (maxPt.Y - minPt.Y) + minPt.Y;
                Point3d pt = new Point3d(x, y, 0);
                Circle circle = new Circle
                {
                    Radius = 20,
                    ColorIndex = 1,
                    Center = pt,
                };
                Flash flash = new Flash(circle);
                dbPoint.Add(new DBPoint(pt));
                flash.FlashUpdate(circle);
                CustomMethod.AddEntities(new List<Entity> { dbPoint[i] });
                System.Windows.Forms.Application.DoEvents();
                pm.MeterProgress();
                Z.ed.UpdateScreen();
                flash.FlashErase();
            }
            pm.Stop();
            documentLock.Dispose();
        }
        //统计管线得长度
        [CommandMethod("TJGXCD")]
        public static void TJGXCD()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            Z.ed.WriteMessage("\n请选择任意一段管线");
            List<Entity> ent = CustomMethod.SelectEntitys();
            List<Line> lines = new List<Line>();
            if (ent == null) return;
            if (ent.Count != 0)
            {
                string layerName = ent[0].GetLayerName();
                PromptSelectionResult psr = Z.ed.SelectAll();
                SelectionSet sSt = psr.Value;
                using (Transaction trans = Z.db.TransactionManager.StartTransaction())
                {
                    foreach (SelectedObject item in sSt)
                    {
                        Entity tempEnt = (Entity)trans.GetObject(item.ObjectId, OpenMode.ForWrite);
                        if (tempEnt.Layer == layerName && tempEnt is Line)
                        {
                            lines.Add((Line)tempEnt);
                            tempEnt.LineWeight = LineWeight.LineWeight030;
                            tempEnt.ColorIndex = 1;
                        }
                    }
                    trans.Commit();
                }
            }
            double sumLength = 0;
            foreach (var item in lines)
            {
                sumLength += item.Length;
            }
            Z.ed.WriteMessage(sumLength.ToString());
            documentLock.Dispose();
        }

        //提取多段线坐标
        [CommandMethod("TQZB")]
        public static void TQZB()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Z.doc.LockDocument();
            List<Entity> ents = SelectTool.SelectEntities();
            List<Polyline> polylines = new List<Polyline>();
            List<int> nums = new List<int>();
            if (ents == null || ents.Count == 0) return;
            foreach (var item in ents)
            {
                if (item is Polyline pl)
                {
                    nums.Add(pl.NumberOfVertices);
                    polylines.Add(pl);
                }
            }
            //系统内部进度条
            ProgressMeter pm = new ProgressMeter();
            pm.SetLimit(polylines.Count - 1);
            pm.Start("正在输出坐标");
            //打开文件对话框
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Filter = "TxT File|*.txt|All File|*.*";
            saveFileDialog.Title = "由多段线生成数据文件";
            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;
            if (fileName == "") return;
            int hs = 0;
            int ds = 0;
            for (int i = 0; i < polylines.Count; i++)
            {
                for (int j = 0; j < nums[i]; j++)
                {
                    Point2d p1 = polylines[i].GetPoint2dAt(j);
                    Z.ed.WriteMessage($"{j},{p1.Y.ToString("0.0000")},{p1.X.ToString("0.0000")}\n");
                    FileWrite.WriteLine(j + "," + p1.Y.ToString("0.0000") + "," + p1.X.ToString("0.0000"), fileName);
                    ds += 1;
                }
                hs += 1;
                pm.MeterProgress();
            }
            Z.ed.WriteMessage($"\n共有{ds}个节点");
            Z.ed.WriteMessage($"\n共有{hs}个实体\n");
            pm.Stop();
            documentLock.Dispose();
        }
        //绘制多段线
        [CommandMethod("HZPL")]
        public static void HZPL()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            string path = CustomMethod.FileNameForOpen("请选择文坐标文件");
            if (path == "") return;
            string[] contens = File.ReadAllLines(path, Encoding.UTF8);
            string[] pointName = new string[contens.Length];
            int[] xh = new int[contens.Length];
            List<int> js = new List<int>();
            List<Point2d> pt = new List<Point2d>();
            int temp = -1;
            for (int i = 0; i < contens.Length; i++)
            {
                string[] tempStrs = contens[i].Split(',');
                xh[i] = Convert.ToInt32(tempStrs[0]);
                pt.Add(new Point2d(Math.Round(Convert.ToDouble(tempStrs[2].ToString()), 4), Math.Round(Convert.ToDouble(tempStrs[1]), 4)));
            }
            for (int i = 0; i < pointName.Length; i++)
            {
                if (temp < xh[i])
                {
                    temp = xh[i];
                }
                else
                {
                    js.Add(temp + 1);
                    temp = 0;
                }
            }
            js.Add(xh[xh.Length - 1] + 1);

            List<Polyline> polylines = new List<Polyline>();
            int JSQ = 0;
            for (int i = 0; i < js.Count; i++)
            {
                polylines.Add(new Polyline());
                for (int j = 0; j < js[i]; j++)
                {
                    polylines[i].AddVertexAt(j, pt[JSQ], 0, 0, 0);
                    JSQ++;
                }
                polylines[i].Closed = true;
            }
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                BlockTable bt = trans.GetObject(Z.db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                for (int i = 0; i < polylines.Count; i++)
                {
                    btr.AppendEntity(polylines[i]);
                    trans.AddNewlyCreatedDBObject(polylines[i], true);
                }
                trans.Commit();
            }
            Z.doc.SendStringToExecute("_zoom e ", true, false, false);
            documentLock.Dispose();
            CustomMethod.GetFocus();
        }
        //一键标注功能---未完成
        [CommandMethod("JGBZJL")]
        public static void JGBZJL()
        {
            Point3d p1 = new Point3d(0, 0, 0);
            Point3d p2 = new Point3d(100, 0, 0);
            Point3d p3 = new Point3d(50, 30, 0);
            ObjectId dimensionStyle = Z.doc.Database.DimStyleTableId;
            AlignedDimension alignedDimension = new AlignedDimension
                (p1, p2, p3, "长度" + p1.DistanceTo(p2).ToString("0.000"), dimensionStyle);
            CustomMethod.AddEntityToModelSpace(Z.db, alignedDimension);
        }
        //推算坐标
        [CommandMethod("TSZB")]
        public static void TSZB()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions ppo = new PromptPointOptions("\n请指定外侧设计点");
            ppo.AllowNone = true;
            PromptPointResult ppr = CustomMethod.GetPoint(ppo);
            Point3d p1 = new Point3d();
            Point3d p2 = new Point3d();
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK) p1 = ppr.Value;
            ppo.Message = "\n请指定内侧设计点";
            ppo.BasePoint = p1;
            ppo.UseBasePoint = true;
            ppr = CustomMethod.GetPoint(ppo);
            if (ppr.Status == PromptStatus.None) return;
            if (ppr.Status == PromptStatus.OK) p2 = ppr.Value;
            Vector3d p = p1.GetVectorTo(p2);
            ppo.Message = "\n请指定外侧实测点";
            ppr = CustomMethod.GetPoint(ppo);
            Point3d p3 = new Point3d();
            if (ppr.Status == PromptStatus.Cancel) return;
            if (ppr.Status == PromptStatus.OK) p3 = ppr.Value;
            Point3d p4 = new Point3d();
            p4 = p3 + p;
            Line l1 = new Line(p3, p4);
            CustomMethod.AddEntityToModelSpace(db, l1);
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\提取坐标点.txt";
            if (!File.Exists(path))
            {
                FileAdd(path, 1 + "," + "," + p4.Y.ToString("0.000") + "," + p4.X.ToString("0.000") + "," + "0" + "\n");
            }
            else
            {
                string[] strings = File.ReadAllLines(path);
                int rowNum = strings.Length;
                FileAdd(path, rowNum + 1 + "," + "," + p4.Y.ToString("0.000") + "," + p4.X.ToString("0.000") + "," + "0" + "\n");
            }
            documentLock.Dispose();
        }
        public static void FileAdd(string path, string strings)
        {
            StreamWriter sw = File.AppendText(path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
        //提取多段线顶点及凸度
        [CommandMethod("TQZBHH")]
        public static void TQZBHH()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            CustomMethod.GetFocus();
            Z.ed.WriteMessage("\n请选择多段线");
            //打开文件对话框
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Filter = "txt files(*.txt)|*.txt|All File(*.*)|*.*";
            saveFileDialog.Title = "由多段线生成数据文件";
            string fileName = "";
            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileName = saveFileDialog.FileName;
            }
            if (fileName == "") return;
            List<Polyline> polylines = SelectTool.SelectEntities<Polyline>();
            List<int> numVertices = new List<int>();
            if (polylines == null || polylines.Count == 0) return;
            //系统进度条
            ProgressMeter pm = new ProgressMeter();
            pm.SetLimit(polylines.Count);
            pm.Start("正在输出坐标");
            for (int j = 0; j < polylines.Count; j++)
            {
                numVertices.Add(polylines[j].NumberOfVertices);
                for (int i = 0; i < numVertices[j]; i++)
                {
                    Point2d tempPt = polylines[j].GetPoint2dAt(i);
                    double bulge = polylines[j].GetBulgeAt(i);
                    FileWrite.WriteLine(i + "," + tempPt.Y + "," + tempPt.X + "," + bulge, fileName);
                }
                pm.MeterProgress();
            }
            pm.Stop();
            documentLock.Dispose();
        }
        //由坐标及凸度绘制多段线
        [CommandMethod("SCFW")]
        public static void SCFW()
        {
            DocumentLock documentLock = Z.doc.LockDocument();
            PromptOpenFileOptions pfo = new PromptOpenFileOptions("打开文件数据对话框");
            pfo.Filter = "txt files(*.txt)|*.txt|All File(*.*)|*.*";
            PromptFileNameResult pfr = Z.ed.GetFileNameForOpen(pfo);
            if (pfr.Status == PromptStatus.OK)
            {
                string strName = pfr.StringResult;
                if (strName == "") return;
                string[] contens = File.ReadAllLines(strName, Encoding.UTF8);
                List<int> xh = new List<int>();
                Point2dCollection pts = new Point2dCollection();
                List<double> bulge = new List<double>();
                List<Polyline> polylines = new List<Polyline>();
                for (int i = 0; i < contens.Length; i++)
                {
                    string[] tempStr = contens[i].Split(new char[] { ',' });
                    xh.Add(Convert.ToInt16(tempStr[0]));
                    pts.Add(new Point2d(Convert.ToDouble(tempStr[2]), Convert.ToDouble(tempStr[1])));
                    bulge.Add(Convert.ToDouble(tempStr[3]));
                }
                List<List<int>> spire = xh.SpireContionsNumbers();
                int spireCount = spire.Count;
                int conter = 0;
                for (int i = 0; i < spireCount; i++)
                {
                    polylines.Add(new Polyline());
                    for (int j = 0; j < spire[i].Count; j++)
                    {
                        polylines[i].AddVertexAt(j, pts[conter], bulge[conter], 0, 0);
                        if (j == spire[i].Count - 1)
                        {
                            polylines[i].Closed = true;
                        }
                        conter++;
                    }
                }
                //将多段线添加到图形数据库中
                using (Transaction trans = Z.db.TransactionManager.StartTransaction())
                {
                    BlockTable bt = trans.GetObject(Z.db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                    foreach (var item in polylines)
                    {
                        btr.AppendEntity(item);
                        trans.AddNewlyCreatedDBObject(item, true);
                    }
                    trans.Commit();
                }
                CustomMethod.SendCommand("_zoom e");
                documentLock.Dispose();
            }
        }
        //删除多段线上的重复顶点
        [CommandMethod("SCDYDD")]
        public static void SCDYDD()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Z.doc.LockDocument();
            PromptSelectionOptions promptSelectionOptions = new PromptSelectionOptions();
            promptSelectionOptions.MessageForAdding = "\n请选择多段线";
            List<Polyline> plines = SelectTool.SelectEntities<Polyline>(promptSelectionOptions);
            if (plines == null || plines.Count() == 0) return;
            List<int> removeIndex = new List<int>();
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                BlockTable bt = trans.GetObject(Z.db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                foreach (Polyline pline in plines)
                {
                    trans.GetObject(pline.Id, OpenMode.ForWrite);
                    if (pline.Closed == true || pline.GetPoint2dAt(0) == pline.GetPoint2dAt(pline.NumberOfVertices - 1))
                    {
                        //这种方式如果最后重复点为偶数点的话会剩下一个点 需要再删一次重复点
                        //另一种思路是记录重复点的位置，倒着删循环变量使用pline.NumberOfVertices
                        pline.RemoveVertexAt(pline.NumberOfVertices - 1);
                        for (int i = pline.NumberOfVertices - 1; i > 0; i--)
                        {
                            if (pline.GetPoint2dAt(i) == pline.GetPoint2dAt(i - 1))
                            {
                                pline.RemoveVertexAt(i);
                            }
                        }
                        //这是解决最后重复点为偶数点的时候 例如1 2 3 4 4 
                        //if (pline.GetPoint2dAt(0) == pline.GetPoint2dAt(pline.NumberOfVertices - 1))
                        //{
                        //    pline.RemoveVertexAt(pline.NumberOfVertices - 1);
                        //}
                        pline.Closed = true;
                        pline.ColorIndex = 1;
                    }
                    else
                    {
                        for (int i = pline.NumberOfVertices - 1; i > 0; i--)
                        {
                            if (pline.GetPoint2dAt(i) == pline.GetPoint2dAt(i - 1))
                            {
                                pline.RemoveVertexAt(i);
                            }
                        }
                        pline.ColorIndex = 1;
                    }
                }
                trans.Commit();

                //foreach (var pline in plines)
                //{
                //    Polyline polyline = new Polyline();
                //    int num = pline.NumberOfVertices;
                //    trans.GetObject(pline.Id, OpenMode.ForWrite);
                //    if (pline.Closed == true||pline.GetPoint2dAt(0)==pline.GetPoint2dAt(num-1))
                //    {     
                //        HashSet<Point2d> sStPoint = new HashSet<Point2d>();
                //        for (int i = 0; i < num; i++)
                //        {
                //            sStPoint.Add(pline.GetPoint2dAt(i));
                //        }
                //        int n = 0;                      
                //        foreach (var item in sStPoint)
                //        {
                //            polyline.AddVertexAt(n,item,0,0,0);
                //            n++;
                //        }                      
                //        polyline.ColorIndex = 1;
                //        polyline.Closed = true;
                //        btr.AppendEntity(polyline);
                //        trans.AddNewlyCreatedDBObject(polyline,true);                                           
                //    }
                //    trans.Commit();
                //}
            }
            documentLock.Dispose();
        }
        //增删多段线上的顶点
        [CommandMethod("ZSJD")]
        public static void ZSJD()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\n请选择多段线";
            List<Polyline> pls = SelectTool.SelectEntities<Polyline>();
            Polyline pl = pls[0];
            if (pl == null) return;
            Z.ed.SetImpliedSelection(new ObjectId[] { pl.ObjectId });
            Z.ed.Regen();
            while (true)
            {
                if (W.GetPoint(out Point3d point, "\n请选择一点"))
                {
                    Point3d po = pl.GetClosestPointTo(point, false);
                    bool onLine = false;
                    if (po.DistanceTo(point) < 0.0000001)
                    {
                        onLine = true;
                    }
                    double p = pl.GetParameterAtPoint(po);
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        pl.ObjectId.GetObject(OpenMode.ForWrite);
                        if (Math.Floor(p) == p)
                        {
                            int num = (int)p;
                            if (onLine)
                            {
                                pl.RemoveVertexAt(num);
                            }
                            else
                            {
                                pl.AddVertexAt(num == 0 ? 0 : num + 1, point.Convert2d(new Plane()), 0, 0, 0);
                            }
                        }
                        else
                        {
                            pl.AddVertexAt((int)Math.Ceiling(p), point.Convert2d(new Plane()), 0, 0, 0);
                        }
                        trans.Commit();
                        if (pl.NumberOfVertices == 1) break;
                    }
                }
                else
                {
                    break;
                }
            }
            documentLock.Dispose();
        }

        //竣工图号
        [CommandMethod("JGTH")]
        public static void JGTH()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            DocumentLock documentLock = doc.LockDocument();
            CustomMethod.GetFocus();
            int num = 1;
            bool flag = true;
            while (flag)
            {
                DBText txt = new DBText();
                DBText txt1 = new DBText();
                txt.HorizontalMode = TextHorizontalMode.TextCenter;
                txt.VerticalMode = TextVerticalMode.TextTop;
                txt.Height = 4;
                txt.TextString = num.ToString();
                txt1.HorizontalMode = TextHorizontalMode.TextCenter;
                txt1.VerticalMode = TextVerticalMode.TextBottom;
                txt1.Height = 4;
                txt1.TextString = "1";
                Circle circle = new Circle();
                Line line = new Line();

                num++;
                JigDBTextZDBH jigDBTextZDBH = new JigDBTextZDBH(txt, txt1, circle, line);
                PromptResult pr = Z.ed.Drag(jigDBTextZDBH);
                if (pr.Status == PromptStatus.OK)
                {
                    Z.ListAddModelSpace(jigDBTextZDBH.GetEntity());
                }
                else if (pr.Status == PromptStatus.Cancel)
                {
                    flag = false;
                }
            }
            documentLock.Dispose();
        }

        [CommandMethod("YZBBZ")]
        public static void YZBBZ()
        {
            Z.doc.Window.Focus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            //创建文字
            DBText upText = new DBText();
            DBText downText = new DBText();
            upText.SetDatabaseDefaults(db);
            downText.SetDatabaseDefaults(db);
            double textHeigth = 5;
            upText.Height = downText.Height = textHeigth;
            //设置对齐
            upText.HorizontalMode = downText.HorizontalMode = TextHorizontalMode.TextLeft;
            upText.VerticalMode = downText.VerticalMode = TextVerticalMode.TextVerticalMid;
            upText.AdjustAlignment(db);
            downText.AdjustAlignment(db);
            //调整位置
            upText.Move(upText.Position, Point3d.Origin + new Vector3d(0, textHeigth * 0.2, 0));
            downText.Move(downText.Position, Point3d.Origin + new Vector3d(0, -textHeigth * 1.2, 0));
            //获取标注位置
            PromptPointResult ppr = Z.ed.GetPoint("\n请选择第一点");
            if (ppr.Status != PromptStatus.OK) return;
            upText.TextString = "X=" + ppr.Value.Y.ToString("0.0000");
            downText.TextString = "Y=" + ppr.Value.X.ToString("0.0000");
            //计算宽度
            double textWidth = Math.Max(upText.GeometricExtents.MaxPoint.X - upText.GeometricExtents.MinPoint.X,
                downText.GeometricExtents.MaxPoint.X - downText.GeometricExtents.MinPoint.X);
            //创建文字线
            Line textLine = new Line(Point3d.Origin, new Point3d(textWidth, 0, 0));
            textLine.SetDatabaseDefaults(db);
            var pt1 = ppr.Value.Ucs2Wcs();
            //var pt1 = ppr.Value.TransformBy(Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem);
            //创建引线
            Line leaderLine = new Line(pt1, Point3d.Origin);
            leaderLine.SetDatabaseDefaults(db);
            //创建拖拽类
            BZJig bZJig = new BZJig(upText, downText, leaderLine, textLine);
            PromptResult pr = Z.ed.Drag(bZJig);
            if (pr.Status != PromptStatus.OK) return;
            CustomMethod.AddEntities(bZJig.GetEntity());
            documentLock.Dispose();
        }
        //Jig单体阵列
        [CommandMethod("JIGDTZL")]
        public static void JIGDTZL()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            Database db = HostApplicationServices.WorkingDatabase;
            Point3d basePoint = Point3d.Origin;
            int num = 0;
            PromptSelectionOptions selectOption = new PromptSelectionOptions();
            selectOption.MessageForAdding = "\n请选择实体";
            List<Entity> entList = SelectTool.SelectEntities<Entity>(selectOption);
            List<Entity> entClone = entList.Select(e => e.Clone() as Entity).ToList();

            if (entList == null || entList == null) return;
            PromptStringOptions pso = new PromptStringOptions("\n请输入要阵列的个数");
            PromptResult pr = Z.ed.GetString(pso);
            if (pr.Status == PromptStatus.OK)
            {
                try
                {
                    num = Convert.ToInt32(pr.StringResult);
                }
                catch (System.Exception)
                {
                    Z.ed.WriteMessage("\n请输入大于0得整数");
                }
            }
            PromptPointOptions ppo = new PromptPointOptions("\n请选择基点");
            PromptPointResult ppr = Z.ed.GetPoint(ppo);
            if (ppr.Status == PromptStatus.OK)
            {
                basePoint = ppr.Value;
            }

            ArrayJig arrayJig = new ArrayJig(basePoint, entList, num);
            PromptResult prJig = Z.ed.Drag(arrayJig);
            if (prJig.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntities(arrayJig.GetEntities());
            }
            documentLock.Dispose();
        }
        //Mtext最佳包围盒
        [CommandMethod("ZJBWH")]
        public static void ZJBWH()
        {
            Application.DocumentManager.MdiActiveDocument.Window.Focus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            List<Entity> ents = SelectTool.SelectEntities();
            if (ents == null || ents.Count == 0) return;
            foreach (var item in ents)
            {
                if (item is MText mtext)
                {
                    mtext.GetBestBoxPoints().DrawPolyLine();
                }
            }
            documentLock.Dispose();
        }
        //选择管线
        [CommandMethod("XZGX")]
        public static void XZGX()
        {
            CustomMethod.GetFocus();
            DocumentLock documentLock = Application.DocumentManager.MdiActiveDocument.LockDocument();
            //全选所有实体
            PromptSelectionResult psr = Z.ed.SelectAll();
            SelectionSet sSt = psr.Value;
            //提示用户选择实体
            PromptEntityOptions peo = new PromptEntityOptions("\n请选择任意一段管线");
            PromptEntityResult per = Z.ed.GetEntity(peo);
            Entity pickent = null;
            if (per.Status != PromptStatus.OK) return;
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                pickent = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Entity;
            }
            List<Entity> ents = new List<Entity>();
            List<ObjectId> ids = new List<ObjectId>();
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId id in sSt.GetObjectIds())
                {
                    Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
                    //图层、颜色、线型
                    if (pickent.Layer == ent.Layer && pickent.Color == ent.Color &&
                        pickent.Linetype == ent.Linetype && pickent.LineWeight == ent.LineWeight
                        && pickent.GetType() == ent.GetType())
                    {
                        ents.Add(ent);
                        ids.Add(ent.Id);
                    }
                }
            }
            if (ids == null) return;
            Z.ed.SetImpliedSelection(ids.ToArray());
            Z.ed.Regen();
            Z.ed.WriteMessage($"\n共选择了{ids.Count}个实体");
            documentLock.Dispose();
        }
        //统计线长
        [CommandMethod("TJXC", CommandFlags.UsePickSet)]
        public static void TJXC()
        {
            PromptSelectionOptions pso = new PromptSelectionOptions();
            pso.MessageForAdding = "\n请选择多段线或直线";
            List<Entity> ents = SelectTool.SelectEntities<Entity>(pso);

        }
        #region 测试用
        private static Flash flash;
        [CommandMethod("NNN")]
        public static void ZZZ()
        {
            Circle circle = new Circle
            {
                Radius = 10,
                ColorIndex = 0,
                Center = new Point3d(0, 0, 0)
            };
            flash = new Flash(circle);
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
            timer.Interval = 100;
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        private static void Timer_Tick(object sender, EventArgs e)
        {
            if (flash._ent.ColorIndex == 0)
            {
                flash._ent.ColorIndex = 1;
                flash.FlashUpdate(flash._ent);
            }
            else
            {
                flash._ent.ColorIndex = 0;
                flash.FlashUpdate(flash._ent);
            }
        }
        //测试CircleJig
        [CommandMethod("CS4")]
        public static void CS4()
        {
            Matrix3d mt = Z.ed.CurrentUserCoordinateSystem;
            Vector3d normal = mt.CoordinateSystem3d.Zaxis;
            //初始化圆
            CircleJig circleJig = new CircleJig(normal);
            //无限循环
            for (; ; )
            {
                //拖拽
                PromptResult resJig = Z.ed.Drag(circleJig);
                //放弃，则退出
                if (resJig.Status == PromptStatus.Cancel)
                {
                    return;
                }
                //确定,则将圆添加到数据库
                if (resJig.Status == PromptStatus.OK)
                {
                    CustomMethod.AddEntityToModelSpace(Z.db, circleJig.GetEntity());
                    break;
                }
            }
        }
        //测试TriangleCircleJig
        [CommandMethod("CS5")]
        public static void CS5()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions optPoint = new PromptPointOptions("\n请指定等边三角形的中心");
            PromptPointResult resPoint = ed.GetPoint(optPoint);
            if (resPoint.Status != PromptStatus.OK) return;
            Point3d cenPt = resPoint.Value;
            //初始化圆，并添加到图形数据库
            Circle circle = new Circle();
            ObjectId cirId = CustomMethod.AddEntityToModelSpace(db, circle);
            //实例化TriangleCircleJig类
            TriangleCircleJig triangleCircleJig = new TriangleCircleJig(cenPt, cirId);
            //拖拽
            PromptResult resJig = ed.Drag(triangleCircleJig);
            //放弃，则退出并删除圆
            if (resJig.Status == PromptStatus.Cancel)
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    circle = (Circle)trans.GetObject(triangleCircleJig.m_CirId, OpenMode.ForWrite);
                    circle.Erase();
                    trans.Commit();
                }
                return;
            }
            //确定，则将等边三角形添加到图形数据库
            if (resJig.Status == PromptStatus.OK)
            {
                CustomMethod.AddEntityToModelSpace(db, triangleCircleJig.GetEntity());
            }
        }
        [CommandMethod("YYY")]
        public static void YYY()
        {
            List<Entity> entities = new List<Entity>();
            string file = @"C:\Users\10635\Desktop\YYY\";
            for (int i = 1; i < 54; i++)
            {
                if (entities.Count > 0)
                {
                    CustomMethod.EraseEntities(entities);
                    entities = new List<Entity>();
                }
                string path = file + i.ToString() + ".jpg";
                using (var bitmap = new System.Drawing.Bitmap(path))
                {
                    int width = bitmap.Width; //获取图片的宽度
                    int heigth = bitmap.Height; //获取照片的高度
                    for (int x = 0; x < width; x = x + 5)
                    {
                        for (int y = 0; y < heigth; y = y + 5)
                        {
                            System.Drawing.Color color = bitmap.GetPixel(x, y);
                            Circle circle = new Circle()
                            {
                                Radius = 2,
                                Center = new Point3d(x, -y, 0),
                                LineWeight = LineWeight.LineWeight060,
                                Color = Autodesk.AutoCAD.Colors.Color.FromRgb(color.R, color.G, color.B)
                            };
                            entities.Add(circle);
                        }
                    }
                }
                CustomMethod.AddEntities(entities);
                CustomMethod.GetDouble("", out double d);
            }
        }
        //测试用
        [CommandMethod("CS6")]
        public static void CS6()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //设置TrueType字体（仿宋体）
                ObjectId styleId = db.AddTextStyle("仿宋体", "simfang.ttf");
                DBText txt1 = new DBText
                {
                    TextString = "仿宋体",
                    TextStyleId = styleId,
                    Height = 2
                };
                //设置SHX字体（romans）
                styleId = db.AddTextStyle("罗马字体", "romans", "gbcbig");
                DBText txt2 = new DBText();
                txt2.TextString = "罗马字体";
                txt2.TextStyleId = styleId;
                txt2.Height = 2;
                //设置SHX字体（romans）
                styleId = db.AddTextStyle("垂直罗马字体", "romans", "gbcbig");
                //设置文字的各种属性
                styleId.SetTextStyleProp(2.0, 0.67, 15 * Math.PI / 180, true, true, true, AnnotativeStates.True, true);
                DBText txt3 = new DBText();
                txt3.TextString = "垂直罗马字体";
                txt3.TextStyleId = styleId;
                //设置TrueType字体(宋体),并且有加粗、倾斜效果
                styleId = db.AddTextStyle("加粗倾斜字体", "宋体", true, true, 0, 0);
                DBText txt4 = new DBText();
                txt4.TextString = "加粗倾斜字体";
                txt4.TextStyleId = styleId;
                db.AddToModelSpace(txt1, txt2, txt3, txt4);
                txt3.SetFromTextStyle();
                trans.Commit();
            }


        }
        #endregion
        [CommandMethod("QQ")]
        public static void M1()
        {
            //选择全图，筛选出单行文字
            PromptSelectionResult psr = Z.ed.SelectAll();
            List<ObjectId> ids = new List<ObjectId>();
            //存储所有的文字
            List<DBText> txts = new List<DBText>();
            //存储桩号文字
            List<DBText> zh = new List<DBText>();
            //存储距离（m）
            List<DBText> jl = new List<DBText>();
            //临时List集合
            List<DBText> temptxts = new List<DBText>();
            //存储桩号和距离
            List<string> zhStr = new List<string>();
            List<string> jlStr = new List<string>();
            if (psr.Status != PromptStatus.OK)
                return;
            ids.AddRange(psr.Value.GetObjectIds());
            using (Transaction trans = Z.db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId id in ids)
                {
                    Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead);
                    if (ent is DBText txt)
                    {
                        txts.Add(txt);
                        if (txt.TextString == "桩 号")
                        {
                            zh.Add(txt);
                        }
                        if (txt.TextString == "距 离（m）")
                        {
                            jl.Add(txt);
                        }
                    }
                }
            }
            temptxts = zh.OrderBy(x => x.Position.X).ToList();
            zh.Clear();
            zh.AddRange(temptxts);
            temptxts.Clear();
            temptxts = jl.OrderBy(x => x.Position.X).ToList();
            jl.Clear();
            jl.AddRange(temptxts);
            //也可以直接读取txt数据更为保险
            foreach (var item in zh)
            {
                zhStr.AddRange(FindTxt(item, txts));
            }

            //相邻的点号相同的去掉一个：这种情况是跨表
            //分组，首尾相接
            foreach (var item in jl)
            {
                jlStr.AddRange(FindTxt(item, txts));
            }
            // 将相邻的桩号相同的去掉一个，这是处理跨表的情况
            RemoveConsecutiveDuplicates(zhStr);
            string tempStr = zhStr[0];
            int num = 0;
            int numbc = 0;
            FileAdd("C:\\Users\\10635\\Desktop\\标称数据.txt", "//桩号,长度，是否为弧长"+"\n");
            for (int i = 0; i < zhStr.Count - 1; i++)
            {
                if (zhStr[i] == tempStr)
                {
                    num++;
                }
                if (num == 2)
                {
                    num = 0;
                    tempStr = zhStr[i + 1];
                    FileAdd("C:\\Users\\10635\\Desktop\\标称数据.txt", zhStr[i] + "\n");
                }
                else
                {
                    if (jlStr[numbc].Contains("弧长"))
                    {
                        FileAdd("C:\\Users\\10635\\Desktop\\标称数据.txt", zhStr[i] + "," + ExtractNumbers(jlStr[numbc]) + "," + "是" + "\n");
                        numbc++;
                    }
                    else
                    {
                        FileAdd("C:\\Users\\10635\\Desktop\\标称数据.txt", zhStr[i] + "," + jlStr[numbc] + "," + "否" + "\n");
                        numbc++;
                    }
                }
            }
            FileAdd("C:\\Users\\10635\\Desktop\\标称数据.txt", zhStr.Last() + "\n");
            Z.ed.WriteMessage("标称数据提取完毕！");
        }
        /// <summary>
        /// 提取字符串中的数字
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <returns>返回一个数字</returns>
        public static string ExtractNumbers(string input)
        {
            StringBuilder sb = new StringBuilder();
            Regex regex = new Regex(@"-?\d+(\.\d+)?");
            MatchCollection matches = regex.Matches(input);
            foreach (Match match in matches)
            {
                sb.Append(match.Value);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 删除连续重复元素之一
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="list">元素集合</param>
        public static void RemoveConsecutiveDuplicates<T>(List<T> list)
        {
            int i = 1;
            while (i < list.Count)
            {
                if (list[i].Equals(list[i - 1]))
                {
                    list.RemoveAt(i);
                    continue;
                }
                i++;
            }
        }
        /// <summary>
        /// 计算对齐点X与该文字相同的文字集合
        /// </summary>
        /// <param name="txt">参照文字</param>
        /// <param name="txts">文字集合</param>
        /// <returns>齐点X与该文字相同的文字集合</returns>
        public static List<string> FindTxt(DBText txt, List<DBText> txts)
        {
            List<DBText> temptxt = new List<DBText>();
            List<DBText> temptxt1 = new List<DBText>();
            List<string> strs = new List<string>();
            for (int i = 0; i < txts.Count; i++)
            {
                if (Math.Round(txts[i].AlignmentPoint.X, 0) == Math.Round(txt.AlignmentPoint.X, 0) &&
                    txts[i].AlignmentPoint != txt.AlignmentPoint && txts[i].TextString != "校 对")
                {
                    temptxt.Add(txts[i]);
                }
            }
            temptxt1 = temptxt.OrderByDescending(x => x.AlignmentPoint.Y).ToList();
            foreach (var item in temptxt1)
            {
                strs.Add(item.TextString);
            }
            return strs;
        }


        public static ObjectIdCollection GetBlockEntityIds(BlockReference blockRef)
        {
            ObjectIdCollection entityIds = new ObjectIdCollection();
            using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
            {
                BlockTableRecord blockRecord = (BlockTableRecord)tr.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead);
                foreach (ObjectId entityId in blockRecord)
                {
                    Entity entity = tr.GetObject(entityId, OpenMode.ForRead) as Entity;
                    if (entity != null && entity.BlockId == blockRef.BlockTableRecord)
                    {
                        entityIds.Add(entityId);
                    }
                }
                tr.Commit();
            }
            return entityIds;
        }













    }
}

